/*
 * Copyright (c) 2020-2021 Jinsp-tech. All rights reserved.
 */

package com.jinsp.skinlib;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;

/**
 * Created by luoshuai on 9/1/21
 * <p>
 * Android轻量级数据存储SharedPreferences工具类，多进程使用
 */
public class SharedPreferencesUtils {

    private static final String NAME = "skin";     //文件名
    private static SharedPreferences mSharedPreferences;
    private static SharedPreferences.Editor mEditor;

    /**
     * 初始化SharedPreference
     *
     * @param context 上下文
     */
    public static void init(Context context) {
        if (mSharedPreferences == null) {
            String name = context.getApplicationContext().getPackageName()
                    .concat("_").concat(NAME);
            mSharedPreferences = context.getApplicationContext().getSharedPreferences(name, Context.MODE_PRIVATE);
        }
    }

    /**
     * 根据key保存对应的字符串value
     *
     * @param key   指定key
     * @param value 对应的value值
     */
    public static void saveStringValue(String key, String value) {
        initEditor();
        mEditor.putString(key, value).apply();
    }

    /**
     * 根据指定key获取对应字符串value
     *
     * @param key          key值
     * @param defaultValue 默认value值
     * @return 获取的value值
     */
    public static String getStringValue(String key, String defaultValue) {
        return mSharedPreferences.getString(key, defaultValue);
    }

    @SuppressLint("CommitPrefEdits")
    private static void initEditor() {
        if (mEditor == null) {
            mEditor = mSharedPreferences.edit();
        }
    }
}
